package com.longxiao.service;

import com.longxiao.service.util.RedisClient;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.longxiao.enums.SysConfigKey;
import com.longxiao.entity.SysConfig;
import com.longxiao.mapper.SysConfigMapper;

@Service("sysConfigService")
public class SysConfigService {

	@Autowired
	SysConfigMapper configMapper;

	@Autowired
	RedisClient redisClient;
	
	Logger logger = LoggerFactory.getLogger(SysConfigService.class);
	
	public SysConfig selectByKeyword(SysConfigKey keyword) {
		SysConfig config = configMapper.selectByKeyword(keyword);
		logger.info("selectByKeyword|keyword:{}|return:{}", keyword, JSON.toJSONString(config));
		return config;
	}
	
	public SysConfig getById(Integer id) {
		return configMapper.selectByPrimaryKey(id);
	}
	
	public String getValByKeyword(SysConfigKey keyword) {
		String key = "syscfg:" + keyword;
		String val = redisClient.get(key);
		if (val != null) {
			logger.info("getValByKeyword|from redis|keyword:{}|return:{}", keyword, val);
			return val;
		} else {
			SysConfig config = configMapper.selectByKeyword(keyword);
			val = config.getVal();
			redisClient.setEx(key, val, 5 * 60);
			logger.info("getValByKeyword|from db|keyword:{}|return:{}", keyword, val);
		}
		return val;
	}

	public String getValByKeyword(SysConfigKey keyword, String defaultVal) {
		String s = getValByKeyword(keyword);
		if (s == null) {
			return defaultVal;
		}
		return s;
	}
	
	public List<SysConfig> getSysConfigList(String key,int offset,int rows) {
		return configMapper.selectList(key, offset, rows);
	}
	
	public int countSysConfigList(String key) {
		return configMapper.countList(key);
	}

	
	public boolean addConfig(SysConfig config) {
		return configMapper.insertSelective(config) > 0;
	}
	
	public boolean updateConfig(SysConfig config) {
		return configMapper.updateByPrimaryKeySelective(config) > 0;
	}
}
